package com.example.javabasic.thread.classtwo.threadlocal.demo5;

import java.util.LinkedList;
//队列
public class MessageQueue {
    private final LinkedList<Message> queue ;

    private final static int DEFAULT_LEMIT = 100;
    private final int limit ;

    public MessageQueue() {
        this(DEFAULT_LEMIT);
    }


    public MessageQueue(final int limit){
        this.queue = new LinkedList<>();
        this.limit = limit;
    }


    public void put(Message message) throws InterruptedException {
        synchronized (queue){
            while(queue.size()>limit){
                queue.wait();
            }
            queue.addLast(message);
            queue.notifyAll();
        }
    }

    public Message take() throws InterruptedException {
        synchronized (queue){
            while(queue.isEmpty()){
                queue.wait();
            }
            Message message = queue.removeFirst();
            queue.notifyAll();
            return message;

        }
    }


    public int getMaxLimit(){
        return limit;
    }


    public int getMessageSize(){
        synchronized (queue){
            return queue.size();
        }
    }

}
